<template>
	<view class="videoWrap">
		<view class="backBottom" :style="capsuleStyle" @click="goBack">
			<cover-image class="back-icon" src="../static/home.png" mode="widthFix"></cover-image>
		</view>

		<!-- 视频播放器 -->
		<block>
			<swiper class="swiper-wrap" vertical="true" circular="true" duration="400" @change="onSwiperChange" @transition="onSwiperOffset">
				<swiper-item v-for="(item,index) in list " :key="index" :id="'feed-'+item.id" class="video-wrap">
					<!-- {{item && item.video && currentIndex < index + 1 && currentIndex > index - 2}} -->
					<video v-if=" item && item.video && currentIndex < index + 1 && currentIndex > index - 2 " :id="'video-'+index"
					 class="video" :src="item.video.resource.url" :autoplay="index === 0" :loop="loop" :muted="index !== currentIndex"
					 :show-fullscreen-btn="false" :show-center-play-btn="false" :direction="0" :controls="false" :data-index="index"
					 @timeupdate="onProgress" @ended="onEnd" object-fit="contain"></video>
				</swiper-item>
			</swiper>

			<view class="bottom-cover"></view>

			<view class="bottom">
				<view class="username">
					<text class="name">{{ feed.user.name }}</text>

					<block v-if="feed.user.verification">
						<image class="icon" :src="'../static/sns/ico_verification_' + feed.user.verification.type +'.png'"></image>
						<text class="desc text-cut">{{ feed.user.verification.slogan }}</text>
					</block>
				</view>
				<view class="content text-cut-2">{{ feed.feed_content || '发布了视频' }}</view>
				<view class="feed" v-if="feed.topics.length">
					<image class="avatar" :src="feed.topics[0].logo.url + '?rule=w_100,h_100'" mode="aspectFill"></image>
					<view class="topic-info">
						<view class="topic-name text-cut">{{ feed.topics[0].name }}</view>
						<!-- <button v-if="access.reward" class="button" bind:tap="onReward">
		          <image class="icon" src="/images/ico_cat_reward@2x.png"></image>打赏
		        </button> -->
						<button class="button" :class="{already:feed.topics[0].has_followed}" @click="onFollowTopic">
							<image class="icon" src="../static/sns/ico_cat_attention@2x.png"></image>{{ feed.topics[0].has_followed ? '已加入' : '加入' }}
						</button>
					</view>
				</view>
				<view class="feeds" v-else></view>
			</view>

			<view class="right">
				<view class="right-wrap user-wrap">
					<image class="avatar" :src="parseAvatarUrl(feed.user)||'../static/sns/pic_default_headphoto@3x.png'" mode="aspectFill"
					 :data-user-id="feed.user.id"></image>
				</view>
				<button class="right-wrap btn" @click="onLike">
					<image class="side-icon" :src="'../static/sns/' +  (feed.has_liked ? 'ico_momentslist_zan_on@2x' : 'ico_video_zan@2x')  + '.png'"></image>
					<view class="text">{{ feed.like_count || '点赞' }}</view>
				</button>
				<button class="right-wrap btn" @click="onComment">
					<image class="side-icon" src="../static/sns/ico_video_comment@2x.png" mode="widthFix"></image>
					<view class="text">{{ feed.feed_comment_count || '评论' }}</view>
				</button>
				<button class="right-wrap btn" open-type="share">
					<image class="side-icon" src="../static/sns/ico_video_share@2x.png" mode="widthFix"></image>
					<view class="text">{{ feed.shares_count || '分享' }}</view>
				</button>
				<button class="right-wrap btn" @click="onMore">
					<view class="text" style="width: 50rpx;">
						<image style="width: 100%;" mode="widthFix" src="../static/sns/white_font@2x.png"></image>
					</view>
				</button>
			</view>
		</block>
		<pop-comment ref="popComment"></pop-comment>
	</view>
</template>

<script>
	import popComment from "../components/popComment/popComment.vue";
	import {
		$storage
	} from '@/utils'
	let preloadLock = false
	export default {
		data() {
			return {
				/** 播放列表 */
				list: [],
				/** 当前播放的视频位于列表的索引 */
				currentIndex: 0,
				/** 当前播放的视频 */
				feed: {},
				/** 上个视频索引 */
				prevIndex: 0,
				logged: {},
				access: {},
				/** 导航条矩阵信息 */
				capsuleStyle: '',
				/** 控制循环播放的变量 */
				loop: true,
				noMore: false
			};
		},
		components:{
			popComment
		},
		watch: {
			currentIndex(newIndex) {
				const oldIndex = this.prevIndex
				if (newIndex === oldIndex) return
				if (oldIndex === this.list.length - 2 && newIndex === this.list.length - 1) {
					this.fetchList()
				}
				preloadLock = false
				const oldVideo = wx.createVideoContext(`video-${oldIndex}`, this)
				oldVideo.pause()
				const newVideo = wx.createVideoContext(`video-${newIndex}`, this)
				newVideo.seek(0)
				newVideo.play()
				this.$set(this, 'feed', this.list[newIndex]);
				this.prevIndex = newIndex
			}
		},
		async onLoad(query) {
			wx.showShareMenu({
			  withShareTicket: true,
			  menus: ['shareAppMessage', 'shareTimeline']
			})
			// if (!GlobalData.access.video) {
			//   wx.showToast({ title: '根据相关规定,无法播放视频', icon: 'none', duration: 1e5 })
			//   return
			// }
			let initDeviceInfo = await this.initDeviceInfo();
			const position = initDeviceInfo.rect
			const {
				height,
				top,
				right
			} = position
			const left = initDeviceInfo.clientWidth - right
			const capsuleStyle = `top: ${top}px;height: ${height}px;left: ${left}px;`
			this.capsuleStyle = capsuleStyle
			const feedId = query.feedId ? +query.feedId : +query.id
			// const feedId = 432
			const excludeStr = query.exclude
			if (excludeStr) {
				let exclude = excludeStr.split(',').map((id) => +id)
				exclude = [...new Set(exclude)]
				this.exclude = exclude;
				this.logged = $storage.get('user') || {};
			}
			await this.fetchFeed(feedId)
			await this.fetchList()
			// $event.on('after:comment', this, () => {
			// 	const index = this.data.currentIndex
			// 	this.setData({
			// 		[`list[${index}].feed_comment_count`]: this.data.list[index].feed_comment_count + 1,
			// 		[`feed.feed_comment_count`]: this.data.list[index].feed_comment_count + 1,
			// 	})
			// })
		},
		methods: {
			onComment() {
			      const feed = this.list[this.currentIndex];
				  this.$refs.popComment.open(feed.id);
			    },
			async initDeviceInfo() {
				let deviceInfo = {}
			    deviceInfo.rect = await wx.getMenuButtonBoundingClientRect()
			    await wx.getSystemInfo({
			      success: (res) => {
			        deviceInfo.clientHeihgt = res.windowHeight
			        deviceInfo.clientWidth = res.windowWidth
			      }
			    })
				return deviceInfo
			  },
			parseAvatarUrl(user) {
				if (!user) return
				const avatar = user.avatar
				if (typeof avatar === 'string') return avatar
				return avatar ? avatar.url : ''
			},
			goBack() {
				const pages = getCurrentPages()
				if (pages.length === 1) {
					wx.switchTab({
						url: '/pages/index'
					})
				} else {
					wx.navigateBack({
						delta: 1
					})
				}
			},
			async onLike() {
				// $event.emit('dGiveUps', { id: this.data.feed.id })
				const index = this.currentIndex
				const feed = this.feed
				console.log(feed.has_liked)

				if (feed.has_liked) {
					await this.$u.api.unlikeFeed(feed.id)
				} else {
					const res = await this.$u.api.likeFeed(feed.id)
					if (res.amount) {
						// $event.emit('showMessage', {
						//   message: '点赞成功',
						//   amount: res.amount,
						// })
						wx.showToast({
							title: '点赞成功'
						})
					}
				}
				// debugger
				let flag = !feed.has_liked;
				this.$set(this.list, 'has_liked', flag)
				this.$set(this.list, 'like_count', feed.like_count + (flag ? 1 : -1))
				this.$set(this.feed, 'has_liked', flag)
				this.$set(this.feed, 'like_count', feed.like_count + (flag ? 1 : -1))
			},
			onProgress(event) {
				if (preloadLock) return
				// 视频预加载
				if (this.currentIndex < this.list.length - 1) {
					const nextVideo = wx.createVideoContext(`video-${this.currentIndex + 1}`, this)
					const lastVideo = wx.createVideoContext(`video-${this.currentIndex - 1}`, this)
					nextVideo.pause()
					lastVideo.pause()
					preloadLock = true
				}
			},
			onEnd() {
				if (this.currentIndex >= this.list.length - 1) {
					wx.showToast({
						title: '没有更多了',
						icon: 'none'
					})
				}
				// 如需自动播放下一个视频打开下面的注释
				// const index = Math.min(this.data.currentIndex + 1, this.data.list.length - 1)
				// this.setData!({
				//   currentIndex: index,
				// })
			},
			onSwiperOffset() {
				wx.createVideoContext(`video-${this.currentIndex}`, this).play()
			},
			onSwiperChange(event) {
				this.currentIndex = event.detail.current
				const nextVideo = wx.createVideoContext(`video-${this.currentIndex + 1}`, this)
				const lastVideo = wx.createVideoContext(`video-${this.currentIndex - 1}`, this)
				nextVideo.pause()
				lastVideo.pause()
			},
			async fetchFeed(feedId) {
				try {
					const feed = await this.$u.api.getFeedDetail(feedId)
					this.feed = feed;
					this.list = [feed];
					this.currentFeedId = feed.id;
				} catch (error) {
					return wx.navigateTo({
						url: `/pages/not-page/not-page?type=${error.statusCode}`,
					})
				}
			},
			async fetchList() {
				if (this.noMore) return
				const exclude = (this.list).map((f) => f.id)
				const list = await this.$u.api.getRandomFeeds({
					only_video: 1,
					exclude_feeds: exclude,
				})
				if (!list.length) {
					this.noMore = true
					return
				}
				this.list = [...this.list, ...list]
			},
			onMore() {
				// deleteFeed
				const userTest = $storage.get("user")
				if (userTest !== undefined) {
					const user = userTest
					const user_id = this.feed.user_id
					const feedId = this.feed.id
					if (user.id === user_id) {
						wx.showActionSheet({
							itemList: ['删除'],
							success: async ({
								tapIndex
							}) => {
								switch (tapIndex) {
									case 0:
										// this.onReportFeed()
										wx.showLoading({
											title: '删除中'
										})
										await this.$u.api.deleteFeed(feedId).then((res) => {
											wx.hideLoading()
											console.log(res)
											// 首页 移除当前动态，总动态条数 -1
											uni.$emit("removeOneFeed",this.feed.id);
											const pages = getCurrentPages()
											const prevPage = pages[pages.length - 2] //上一个页面
											prevPage.setData({
												mydata: {
													type: 'new',
												},
											})
											wx.navigateBack({
												//返回
												delta: 1,
											})

										})
										break
								}
							},
						})
					} else {
						const id = this.feed.id
						wx.showActionSheet({
							itemList: ['举报'],
							success: ({
								tapIndex
							}) => {
								switch (tapIndex) {
									case 0:
										// this.onReportFeed()
										wx.navigateTo({
											url: `/feed/report?type=feed&id=${id}`,
										})
										break
								}
							},
						})
					}
				} else {
					$event.emit('login')
				}
			},
		}
	};
</script>

<style lang="scss">
	@import '../var';
	@import '../common';

	page {
		position: fixed;
		height: 100%;
		background-color: $black-color;
	}
	.btn::after {
	  border: 0;
	}
	.videoWrap {
		height: 100%;
	}

	.backBottom {
		position: fixed;
		z-index: $zindex-capsule;
		display: flex;
		align-items: center;
		justify-content: center;
		box-sizing: border-box;
		width: 100rpx;
		height: 50rpx;
		padding-left: 4rpx;
	}

	.back-icon {
		width: 32rpx;
		height: auto;
	}

	.swiper-wrap {
		height: 100%;
	}

	.video-wrap {
		width: 100%;
		height: 100%;

		swiper {
			width: 100%;
			height: 100%;
		}

		.video {
			position: relative;
			width: 100%;
			height: 100%;
		}
	}

	.bottom-cover {
		position: fixed;
		bottom: 0;
		width: 100%;
		height: 33vh;
		background: linear-gradient(transparent, rgba($black-color, 0.4));
		pointer-events: none;
	}

	.bottom {
		position: fixed;
		bottom: $xl;
		left: $xl;
		display: flex;
		flex-direction: column;
		width: 539rpx;
		color: $bgcolor-light;

		.username {
			display: flex;
			align-items: center;
			max-width: 100%;
			margin-bottom: 23rpx;
			font-weight: 500;
			font-size: 34rpx;

			.name {
				display: inline-block;
			}

			.icon {
				width: 34rpx;
				height: 34rpx;
				margin-right: 8rpx;
				margin-left: 21rpx;
			}

			.desc {
				max-width: 13em;
				height: 1.23em;
				font-size: 22rpx;
				transform: translateY(3rpx);
			}
		}

		.content {
			font-size: 30rpx;
		}

		.feeds {
			width: 100rpx;
			height: 60rpx;
			margin-top: 29rpx;
		}

		.feed {
			display: flex;
			align-items: center;
			margin-top: 29rpx;

			.avatar {
				flex: none;
				width: 60rpx;
				height: 60rpx;
				margin-right: 19rpx;
				border-radius: 10rpx;
			}

			.topic-info {
				display: flex;
				align-items: center;

				.topic-name {
					max-width: 8em;
				}

				.button {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 120rpx;
					height: 48rpx;
					margin-left: 18rpx;
					padding: 0;
					color: #fff;
					font-size: 24rpx;
					line-height: 48rpx;
					background-color: $primary-color;
					border-radius: 24rpx;
					transition: color 0.4s, transform 0.6s 0.4s;

					&.already {
						color: $bgcolor-light;
						transform: scale(0);
					}
				}

				.icon {
					width: 24rpx;
					height: 24rpx;
					margin-right: 5rpx;
				}
			}
		}
	}

	.right {
		position: absolute;
		right: $md;
		bottom: 10vh;
		z-index: 100;
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 90rpx;
		font-size: $font-size-small;

		cover-view {
			text-align: center;
		}

		.right-wrap {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin: 0 0 $xl;
			color: $bgcolor-light;
			font-size: $font-size-small;
			background-color: transparent;

			&:first-child {
				height: 130rpx;
			}

			.avatar {
				box-sizing: border-box;
				width: 90rpx;
				height: 90rpx;
				border: 4rpx solid $bgcolor;
				border-radius: 100rpx;
			}

			.follow-btn {
				position: relative;
				top: -16rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 40rpx;
				height: 40rpx;
				padding: 0;
				color: $primary;
				background-color: $bgcolor;
				border: 2rpx solid currentColor;
				border-radius: 40rpx;

				.plus {
					font-weight: bold;
					font-size: $font-size-small;
					line-height: 40rpx;
					vertical-align: bottom;
				}
			}

			.side-icon {
				display: block;
				width: 60rpx;
				height: 53rpx;
				margin-bottom: 6rpx;
			}

			.text {
				line-height: 1.2;
			}
		}
	}
</style>
